package com.mac.intellect_flow.framework.service;

import com.google.common.collect.Sets;
import com.mac.intellect_flow.enums.ResultCodeEnum;
import com.mac.intellect_flow.enums.UserStateEnum;
import com.mac.intellect_flow.except.ServiceException;
import com.mac.intellect_flow.framework.dto.SysUserDto;
import com.mac.intellect_flow.framework.security.handle.SimGrantedAuthority;
import com.mac.intellect_flow.framework.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户验证处理
 *
 * @author mac
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private CurSysUserService userService;
    
    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private CurPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDto user = userService.selectUserByUserName(username);
        if (Objects.isNull(user)) {
            log.error("登录用户：{} 不存在.", username);
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"用户不存在");
        } else if (UserStateEnum.DISABLE.getCode().equals(user.getStatus())) {
            log.error("登录用户：{} 已被停用.", username);
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"用户被停用");
        }
        passwordService.validate(user);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUserDto sysUser) {
        LoginUser user = new LoginUser();
        user.setId(sysUser.getId());
        user.setUsername(sysUser.getUsername());
        user.setPassword(sysUser.getPassword());
        user.setDeptId(sysUser.getDeptId());
        user.setPermissions(permissionService.getMenuPermission(sysUser));
        user.setRoles(permissionService.getRolePermission(sysUser));
        if (sysUser.isAdmin()){
            user.setAuthorities(Sets.newHashSet(new SimGrantedAuthority("ROLE_ADMIN"),new SimGrantedAuthority("ADMIN")));
        }else {
            user.setAuthorities(Sets.newHashSet(new SimGrantedAuthority("ROLE_USER")));
        }
        return user;
    }
}
